/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reyes.mysite.servlet;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.methods.HeadMethod;
import reyes.mysite.dao.GenericDAO;
import reyes.mysite.jdo.Blog;
import reyes.mysite.jdo.Category;
import org.json.JSONArray;
import org.json.JSONObject;
import reyes.mysite.helper.MethodHelper;

/**
 *
 * @author reyesyang
 */
public class publicBlogServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try {
            String task = request.getParameter("task");
            if (task.equals("getAllCategories")) {
                getAllCategories(request, response);
            } else if (task.equals("getAllDates")) {
                getAllDates(request, response);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void getAllCategories(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setHeader("Pragam", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        response.setContentType("text/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        try {
            JSONObject json = new MethodHelper().getAllCategoriesJSON();
            out.append(json.toString());
        } catch (Exception e) {
            System.out.println("Can't get all category: Details: " + e.getMessage());
        } finally {
            out.close();
        }
    }

    public void getAllDates(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        JSONObject json = new JSONObject();
        GenericDAO<Blog> blogDAO = new GenericDAO<Blog>();

        try {
            String queryString = "select from " + Blog.class.getName() + " order by date desc";
            List<Blog> blogs = blogDAO.query(queryString);

            for (Blog blog : blogs) {
                Date date = blog.getDate();

                String year = String.valueOf(date.getYear() + 1900);
                String month = String.valueOf(date.getMonth() + 1);

                if (json.isNull(year)) {
                    JSONObject jsonYear = new JSONObject();
                    jsonYear.put(month, 1);
                    jsonYear.put("total", 1);
                    json.put(year, jsonYear);
                } else {
                    JSONObject jsonYear = (JSONObject) json.get(year);

                    if (jsonYear.isNull(month)) {
                        jsonYear.put(month, 0);
                        jsonYear.put("total", (jsonYear.getInt("total")) + 1);
                    } else {
                        jsonYear.put(month, (jsonYear.getInt(month)) + 1);
                        jsonYear.put("total", (jsonYear.getInt("total")) + 1);
                    }
                }
            }

            out.append(json.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            blogDAO.closePM();
            out.close();
        }
    }
}
